package com.alfayun.fiscalriskanalysis.importer;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alfayun.fiscalriskanalysis.util.DateTimeUtils;

@Service
public final class ImporterService {

	@Value("#{T(java.nio.file.Path).of(\"${application.upload-dir}\")}")
	private Path uploadRoot;

	public Path storeFile(MultipartFile file) throws IOException {
		Path path = genFileStorePath(Path.of(file.getOriginalFilename()).getFileName());

		file.transferTo(path);

		return path;
	}

	private Path genFileStorePath(Path filename) throws IOException {
		final String currentYearAndMonth = DateTimeUtils.yearMonthNow().toString();
		final String newFilename = String.format("%d-%s", DateTimeUtils.instantNow().toEpochMilli(), filename);

		return Files.createDirectories(uploadRoot.resolve(currentYearAndMonth)).resolve(newFilename);
	}

}
